// 记录全部学生
let studentObj;
const tbody = document.querySelector('tbody');
// 获取全部学员信息
getScore();
function getScore() {
  axios.get('/score/list').then((res) => {
    if (res.data.code === 0) {
      studentObj = res.data.data;
      // console.log(studentObj);
      let oHtml = '';
      let score = '';

      for (const key in studentObj) {
        score = studentObj[key].score.reduce((h, v, i) =>
          h +
          `
        <td class="score">
        ${v}
        <input type="text" data-index="${i + 1}" data-id="${key}">
        </td>
        `,
          ''
        );
        oHtml += `
        <tr>
          <th scope="row">${key}</th>
          <td>${studentObj[key].name}</td>
          ${score}
        </tr>
        `;
        tbody.innerHTML = oHtml;
      }
      const inputs = document.querySelectorAll('tbody input');
      inputs.forEach((input) => {
        input.addEventListener('blur', function () {
          const data = {
            stu_id: input.dataset.id,

            batch: input.dataset.index,

            score: input.value
          };

          if (Number(data.score)) {
            // 发送修改请求
            axios.post('/score/entry', data).then((res) => {
              if (res.data.code === 0) {
                toastr.success(res.data.message);
                getScore();
              }
            });
          } else {
            toastr.error('格式不正确');
            getScore();
          }
        });
      });
    }
  });
}
// 双击修改表单
tbody.addEventListener('dblclick', function (e) {
  if (e.target.nodeName === 'TD' && e.target.classList.contains('score')) {
    const input = e.target.children[0];
    input.style.display = 'block';
    input.value = e.target.innerText;
    input.focus();
  }
});
